package com.xpalive.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xpalive.base.mapper.MyBaseMapper;
import com.xpalive.base.service.MyBaseService;
import com.xpalive.utils.ListPrune;
import java.util.List;
import java.util.function.Function;

public abstract class MyBaseServiceImpl<M extends MyBaseMapper<T>, T> extends
    ServiceImpl<M, T> implements
    MyBaseService<T> {

    @Override
    public MyBaseMapper<T> getMyBaseMapper() {
        return getBaseMapper();
    }

    @Override
    public <R> void updateRef(List<T> oldList, List<T> newList, Function<T, R> getIdentity) {
        M mapper = getBaseMapper();
        ListPrune<T, R> listPrune = new ListPrune<>(oldList, newList, getIdentity);
        listPrune.getAddList().forEach(mapper::insert);
        listPrune.getRemoveList().forEach(item -> mapper.delPermanent(Wrappers.lambdaQuery(item)));
    }

    @Override
    public <R> void updateRef(List<T> oldList, List<T> newList, Function<T, R> getIdentity,
        Function<T, LambdaUpdateWrapper<T>> updateWrapper) {
        M mapper = getBaseMapper();
        ListPrune<T, R> listPrune = new ListPrune<>(oldList, newList, getIdentity);
        listPrune.getAddList().forEach(mapper::insert);
        listPrune.getRemoveList().forEach(item -> mapper.delPermanent(Wrappers.lambdaQuery(item)));
        listPrune.getKeepList().forEach(item -> mapper.update(item, updateWrapper.apply(item)));
    }
}
